﻿using Propro.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Data;
using PagedList;
using WebMatrix.WebData;
using System.Data.Entity;
using System.Net.Mail;

namespace Propro.Controllers
{
    [Authorize(Roles = "Administration")]
    public class AdminController : Controller
    {
        public DbSet<Admin.webpages_Membership> webpages_Memberships { get; set; }
        private ProWebContext _db = new ProWebContext();
        public ActionResult Index()
        {
            var model = _db.Users.OrderByDescending(l => l.UserId).Where(u => u.UserName != "Administrator");
            return View(model);
        }
        

        [HttpGet]
        public ActionResult Edit(int id)
        {
            var user = _db.Users.Find(id);
            var temp = new AdminEdit();
            temp.FirstName = user.FirstName;
            temp.LastName = user.LastName;
            temp.UserName = user.UserName;
            temp.UserId = user.UserId;
            temp.Mail = user.Mail;
            temp.Birthday = user.Birthday;
            
            if (Roles.IsUserInRole(user.UserName, "Administration"))
            {
                temp.Admin = true;
            }
            else
            {
                temp.Admin = false;
            }
            return View(temp);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(AdminEdit temp)
        {
            if (ModelState.IsValid)
            {
                var user = _db.Users.Find(temp.UserId);
                user.UserName = temp.UserName;
                user.FirstName = temp.FirstName;
                user.LastName = temp.LastName;
                user.Mail = temp.Mail;
                user.Birthday = temp.Birthday;
                if (temp.Admin == true && !(Roles.IsUserInRole(user.UserName, "Administration")))
                {
                    Roles.AddUserToRole(temp.UserName, "Administration");
                }
                else if (temp.Admin == false && Roles.IsUserInRole(user.UserName, "Administration"))
                {
                    Roles.RemoveUserFromRole(temp.UserName, "Administration");
                }
                _db.Entry(user).State = EntityState.Modified;
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(temp);
        }

       
    }
}
